package com.liu.webstore.service.impl;

import com.liu.webstore.common.Constant;
import com.liu.webstore.entity.LoginTicket;
import com.liu.webstore.entity.User;
import com.liu.webstore.repository.LoginTicketMapper;
import com.liu.webstore.repository.UserMapper;
import com.liu.webstore.service.UserService;
import com.liu.webstore.enums.StatusEnum;
import com.liu.webstore.util.MailClient;
import com.liu.webstore.util.RedisKeyUtil;
import com.liu.webstore.util.WebstoreUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author LiuYumei
 * @Date 2022/7/11 23:19
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${webstore.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private UserMapper userMapper;

    //@Autowired
    //private LoginTicketMapper loginTicketMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public User getUserById(int id) {
        //return userMapper.selectUserById(id);

        User user = getCache(id);
        if (Objects.isNull(user)) {
            user = initCache(id);
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        if (null == user) {
            map.put("errorMsg", "用户信息不能为空！");
            return map;
        }
        if (StringUtils.isEmpty(user.getUsername())) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        if (StringUtils.isEmpty(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空！");
            return map;
        }
        // 验证账号
        User u = userMapper.selectUserByName(user.getUsername());
        if (null != u) {
            map.put("usernameMsg", "该用户名已存在！");
            return map;
        }
        u = userMapper.selectUserByEmail(user.getEmail());
        if (null != u) {
            map.put("emailMsg", "该邮箱已被注册！");
            return map;
        }
        // 注册用户
        user.setSalt(WebstoreUtil.getUuid().substring(0, 6));
        user.setPassword(WebstoreUtil.getMd5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(WebstoreUtil.getUuid());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        int row = userMapper.insertUser(user);
        if (row < 0) {
            map.put("errorMsg", "出现异常！");
            return map;
        }
        // 激活邮件发送
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        // http://localhost:8888/webstore/activation/{userId}/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账户", content);
        return map;
    }

    @Override
    public int activation(int userId, String code) {
        User user = userMapper.selectUserById(userId);
        if (user.getStatus() == 1) {
            return StatusEnum.ACTIVATION_REPEAT.getStatus();
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            clearCache(userId);
            return StatusEnum.ACTIVATION_SUCCESS.getStatus();
        } else {
            return StatusEnum.ACTIVATION_FAILURE.getStatus();
        }
    }

    @Override
    public Map<String, Object> login(String username, String password, int expireSeconds) {
        Map<String, Object> map = new HashMap<>();
        // 空值处理
        if (username == null) {
            map.put("usernameMsg", "用户名不能为空！");
            return map;
        }
        if (password == null) {
            map.put("passwordMsg", "密码不能为空！");
            return map;
        }
        // 账号判断
        User user = userMapper.selectUserByName(username);
        if (Objects.isNull(user)) {
            map.put("usernameMsg", "该账号不存在！");
            return map;
        }
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活！");
            return map;
        }

        password = WebstoreUtil.getMd5(password + user.getSalt());
        if (!Objects.equals(password, user.getPassword())) {
            map.put("passwordMsg", "密码输入错误！");
            return map;
        }
        // 生成登陆凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(WebstoreUtil.getUuid());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expireSeconds * 1000L));
        loginTicket.setStatus(0);
        //int row = loginTicketMapper.insertLoginTicket(loginTicket);
        //if (row < 1) {
        //    map.put("errorMsg", "登录凭证添加失败！");
        //}

        String ticketKey = RedisKeyUtil.getTicketKey(loginTicket.getTicket());
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
        map.put("ticket", loginTicket.getTicket());
        return map;
    }

    @Override
    public void logout(String ticket) {
        //loginTicketMapper.updateLoginTicket(ticket, 1);

        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(ticket);
        if (Objects.nonNull(loginTicket)) {
            loginTicket.setStatus(1);
        }
        redisTemplate.opsForValue().set(ticketKey, loginTicket);
    }

    @Override
    public LoginTicket findLoginTicket(String ticket) {
        String ticketKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(ticketKey);

        //return loginTicketMapper.selectByTicket(ticket);
    }

    @Override
    public int updateHeadPhoto(int userId, String headerUrl) {
        int rows = userMapper.updateHeader(userId, headerUrl);
        clearCache(userId);
        return rows;
    }

    @Override
    public int updatePassword(int userId, String newPwd) {
        int rows = userMapper.updatePassword(userId, newPwd);
        clearCache(userId);
        return rows;
    }

    @Override
    public User findByName(String toName) {
        return userMapper.selectUserByName(toName);
    }

    /**
     * 优先从缓存中去用户信息
     */
    public User getCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    /**
     * 取不到用户信息则初始化缓存数据
     */
    public User initCache(int userId) {
        User user = userMapper.selectUserById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 清除数据
     */
    public void clearCache(int userId) {
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = userMapper.selectUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add((GrantedAuthority) () -> {
            switch (user.getType()) {
                case 1:
                    return Constant.AUTHORITY_ADMIN;
                case 2:
                    return Constant.AUTHORITY_MODERATOR;
                default:
                    return Constant.AUTHORITY_USER;
            }
        });
        return list;
    }
}
